package com.example.springbootlearn.config;
import com.example.springbootlearn.entity.MyselfMapper;
import com.example.springbootlearn.util.AnnotationUtil;
import com.example.springbootlearn.util.Dom4jUtil;
import org.dom4j.Document;
import java.io.File;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Set;

/**
 * 解析封装框架配置文件
 */
public class ORMConfig {
    /**
     * classpath 路径
     */
    private static String classpath;
    /**
     * 核心配置文件
     */
    private static File cfgfile;
    /**
     * 标签中的数据
     */
    private static Map<String, String> propConfig;
    /**
     * 映射文件路径
     */
    private static Set<String> mappingSet;
    /**
     * 实体类
     */
    private static Set<String> entitySet;
    /**
     * 映射信息
     */
    public static List<MyselfMapper> mapperList;

    static {
        // 得到classpath路径
        classpath = Thread.currentThread().getContextClassLoader().getResource("").getPath();
        // 针对中文路径进行转码
        try {
            classpath = URLEncoder.encode(classpath, "utf-8");
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        // 得到核心配置文件
        System.out.println(classpath);
        cfgfile = new File(classpath + "miniORM.cfg.xml");
        if (cfgfile.exists()) {
            Document document = Dom4jUtil.getXMlByFilePath(cfgfile.getPath());
            propConfig = Dom4jUtil.Elements2Map(document, "property", "name");
            mappingSet = Dom4jUtil.Elements2Set(document, "mapping", "resource");
            entitySet =Dom4jUtil.Elements2Set(document, "entity", "package");
        } else {
            cfgfile = null;
            System.out.println("未找到核心配置文件 miniOrm.cfg.xml");
        }
    }
    // 从配置文件中获取 数据库信息并连接数据库
    private Connection connection() throws ClassNotFoundException, SQLException {
        String driveClass = propConfig.get("connection.driverClass");
        String url = propConfig.get("connection.url");
        String root = propConfig.get("connection.username");
        String password = propConfig.get("connection.password");
        Class.forName(driveClass);
        Connection connection = DriverManager.getConnection(url,root,password);
        connection.setAutoCommit(true);
        return connection;
    }

    private void getmapping() throws ClassNotFoundException {
        mapperList = new ArrayList<>();
        // 解析mapper.xml文件获取映射数据
        for (String xmlpath: mappingSet){
            Document xMlByFile = Dom4jUtil.getXMlByFilePath(classpath + xmlpath);
            String className = Dom4jUtil.getPropValue(xMlByFile, "class", "name");
            String tableName = Dom4jUtil.getPropValue(xMlByFile, "class", "table");
            Map<String, String> id2Map = Dom4jUtil.ElementsID2Map(xMlByFile);
            Map<String, String> columnMap = Dom4jUtil.Elements2Map(xMlByFile);

            MyselfMapper mapper = new MyselfMapper();
//            mapper.setIdMapper(id2Map);
//            mapper.setTableName(tableName);
//            mapper.setClassName(className);
//            mapper.setPropMapper(columnMap);

            mapperList.add(mapper);
        }

        // 通过解析实体类中的注解获取映射数据
        for (String packagepath: entitySet) {
            Set<String> nameSet = AnnotationUtil.getClassNameByPackage(packagepath);
            for (String name: nameSet) {
                Class<?> clz = Class.forName(name);
                String tableName = AnnotationUtil.getTableName(clz);
                String className = AnnotationUtil.getClass(clz);
                Map<String, String> mapping = AnnotationUtil.getMapper(clz);
                Map<String, String> propMapping = AnnotationUtil.getPropMapping(clz);

                MyselfMapper mapper = new MyselfMapper();
//                mapper.setTableName(tableName);
//                mapper.setClassName(className);
//                mapper.setIdMapper(mapping);
//                mapper.setPropMapper(propMapping);

                mapperList.add(mapper);
            }
        }
    }
    // 创建ORMSession对象
    public ORMSession buildSession() throws SQLException, ClassNotFoundException {
        // 连接数据库
        Connection connection = connection();
        // 获取映射数据
        getmapping();
        return new ORMSession(connection);
    }
}

